<?php
/**
 * Created by PhpStorm.
 * User: zhang
 * Date: 2016/3/9
 * Time: 23:08
 */
namespace Chealth\Controller;

use Think\Controller;
use User\Model\UcenterMemberModel;

class IndexController extends Controller{
    private $uid;
    private $allow_edit_info;

    public function _initialize(){
        if(is_mobile()){
            # TODO 正式提交时改为正式服务器的地址
            header('Location: /mobile.html');
            exit;
        }
        if (is_login() <= 0) {
            redirect(U('Ucenter/member/login'));
        }
        $this->uid = get_uid();
        $this->defaultUser();
        define('NOW_TIME_FORMAT', strtotime(date('Y-m-d')));
        $this->assign('allow_time', strtotime('+ '.C('CHEALTH_UPDATE_LIMIT_DAY').' day'));
    }

    

    public function index($page = 1, $r = 20){
        $user = M('UcenterMember')->find($this->uid);
        //查找所有预约项目
        $ChealthTimeModel = D('Chealth/ChealthTime');

        list($list,$totalCount) = $ChealthTimeModel->getListByPage('' ,$page, 'id DESC', '*',20);

        $model = D('Chealth/ChealthEnter');
        foreach ($list as $k => $v) {
            $info = $model->where(array('aid'=>$v['id'],'uid'=>$this->uid))->find();
            $list[$k]['status'] = 0;
            //非女性不显示妇科体检
            if($v['type'] == 2 && $user['sex'] != 0){
                unset($list[$k]);
                continue;
            }
            if(!empty($info)){
                $list[$k]['aid'] = $v['id'];
                $list[$k]['id'] = $info['id'];
                $list[$k]['update_num'] = $info['update_num'];
                $list[$k]['chealth_time'] = $info['chealth_time'];
                $list[$k]['status'] = $info['status'];
                $list[$k]['status_text'] = C('FRONT_HEALTH_ENTER_STATUS');
                $list[$k]['status_text'] = $list[$k]['status_text'][$info['status']];
                $list[$k]['file1'] = $info['file1'];
                $list[$k]['file2'] = $info['file2'];
                //检查是否可以编辑
                $list[$k]['allow_edit'] = $this->check_allow_edit($info);
                $list[$k]['allow_edit_info'] = $this->allow_edit_info;
            }
        }

        $this->assign('list', $list);
        $this->assign('totalCount',$totalCount);
        $this->display();
    }

    /**
     * 报名
     */
    public function enter(){
        //获取用户信息
        $user = M('UcenterMember')->find($this->uid);
        //检查用户状态,status为5时不能报名
        if($user['status'] == 5){
            $this->error('无法报名');
        }
        $aid = I('aid', '', 'intval');
        if(empty($aid)){
            $this->error('参数错误!');
        }
        $this->assign('aid', $aid);
        $model = D('Chealth/ChealthEnter');
        //检查是否已经报名
        $getinfo = $model->where(array('uid'=>$this->uid,'aid'=>$aid))->find();
        if(!empty($getinfo)){
            $this->error('您已报名过,请勿重复报名!');
        }
        //获取预约报名项目信息
        $ainfo = D('Chealth/ChealthTime')->getInfoById($aid);
        if(empty($ainfo)){
            $this->error('暂无预约项目', U('index'));
        }
        if(IS_POST){
            $_POST['uid'] = $this->uid;
            $_POST['unit'] = $ainfo['unit'];
            $_POST['name'] = $user['real_name'];
            $_POST['sign'] = $user['username'];
            $_POST['sex'] = $user['sex'];
            $_POST['card'] = $user['card'];
            $_POST['birthdate'] = strtotime($user['birthdate']);
            $result = $model->updateEnter();
            if (!$result) {
                $this->error($model->getError());
            }
            //清空缓存
            S('enterList_'.$ainfo['id'], NULL);
            //更新用户部门信息和手机号信息
            $userdata = array(
                'mobile' => $_POST['mobile'],
                'department_id' => $_POST['department_id']
            );
            M('UcenterMember')->where(array('id'=>$this->uid))->save($userdata);
            //返回成功信息
            $this->success('预约成功', U('index'));
        }else{
            //获取部门信息
            $lists = $dmaplist = D('ChealthDepartment')->select();
            $dmap = array();
            foreach ($lists as $key => $value) {
                $dmap[$value['id']] = $value['name'];
            }
            //获取分组列表
            $lists = D('ChealthGroups')->select();
            $gmap = array();
            foreach ($lists as $key => $value) {
                $gmap[$value['id']] = $value['name'];
            }
            //处理不可查体时间
            $enterList = S('enterList_'.$ainfo['id']);
            if(empty($enterList)){
                if($ainfo['type'] == 1){
                    $enterList = $this->getEnterList($ainfo);
                }else{
                    $enterList = $this->getEnterListFu($ainfo);
                }
                //缓存可报名时间和已报名人数
                S('enterList_'.$ainfo['id'], $enterList);
            }
            $ainfo['enterList'] = $enterList;
            //处理查体项目
            if(!empty($ainfo['chealth_project'])){
                $len = count($ainfo['chealth_project']);
                $chealth_project = array();
                for($i = 0; $i < $len; $i += 2){
                    $chealth_project[] = array(
                        'name' => $ainfo['chealth_project'][$i],
                        'cost' => $ainfo['chealth_project'][$i+1]
                    );
                }
                $ainfo['chealth_project'] = $chealth_project;
            }
            //自动填写用户信息
            $content = array(
                'aid' => $aid,
                'mobile' => $user['mobile'],
                'groups_id' => $user['groups_id'],
                'department_id' => $user['department_id'],
                'chealth_time' => strtotime('+1 minute', $ainfo['check_start_time']),
            );
            $this->assign('userinfo', $user);
            $this->assign('ainfo', $ainfo);
            $this->assign('content', $content);
            $this->assign('dmap', $dmap);
            $this->assign('dmaplist', $dmaplist);
            $this->assign('gmap', $gmap);
            $this->display();
        }
    }

    /**
     * 修改报名
     */
    public function editEnter(){
        $aid = I('aid', '', 'intval');
        if(empty($aid)){
            $this->error('参数错误!');
        }
        $this->assign('aid', $aid);
        $model = D('Chealth/ChealthEnter');
        //检查是否已经报名
        $getinfo = $model->where(array('uid'=>get_uid(),'aid'=>$aid))->find();
        if(empty($getinfo)){
            $this->error('您未报名!');
        }
        if($getinfo['update_num'] >= C('LIMIT_UPDATE_NUM')){
            $this->error('修改次数已使用完,无法修改,请联系管理员');
        }
        $allow_edit = $this->check_allow_edit($getinfo);
        if($allow_edit == 0){
            $this->error($this->allow_edit_info);
        }
        //获取预约报名项目信息
        $ainfo = D('Chealth/ChealthTime')->getInfoById($aid);
        if(empty($ainfo)){
            $this->error('暂无预约项目', U('index'));
        }
        //获取用户信息
        $user = M('UcenterMember')->find($this->uid);
        if(IS_POST){
            $_POST['uid'] = $this->uid;
            //添加一次修改次数
            $_POST['update_num'] = $getinfo['update_num'] + 1;
            $result = $model->updateEnter();
            if (!$result) {
                $this->error($model->getError());
            }
            S('enterList_'.$ainfo['id'], NULL);
            //返回成功信息
            $this->success('修改预约成功', U('index'));
        }else{
            //获取部门信息
            $lists = $dmaplist = D('ChealthDepartment')->select();
            $dmap = array();
            foreach ($lists as $key => $value) {
                $dmap[$value['id']] = $value['name'];
            }
            //获取分组列表
            $lists = D('ChealthGroups')->select();
            $gmap = array();
            foreach ($lists as $key => $value) {
                $gmap[$value['id']] = $value['name'];
            }
            //获取预约报名项目信息
            $ainfo = D('Chealth/ChealthTime')->getInfoById($aid);
            if(empty($ainfo)){
                $this->error('暂无预约项目', U('index'));
            }
            //处理不可查体时间
            $enterList = S('enterList_'.$ainfo['id']);
            if(empty($enterList)){
                if($ainfo['type'] == 1){
                    $enterList = $this->getEnterList($ainfo);
                }else{
                    $enterList = $this->getEnterListFu($ainfo);
                }
                //缓存可报名时间和已报名人数
                S('enterList_'.$ainfo['id'], $enterList);
            }
            $ainfo['enterList'] = $enterList;
            //处理查体项目
            if(!empty($ainfo['chealth_project'])){
                $len = count($ainfo['chealth_project']);
                $chealth_project = array();
                $user_project = explode(',', $getinfo['project']);
                for($i = 0; $i < $len; $i += 2){
                    $chealth_project[] = array(
                        'name' => $ainfo['chealth_project'][$i],
                        'cost' => $ainfo['chealth_project'][$i+1],
                        'is_checked' => in_array($ainfo['chealth_project'][$i], $user_project)
                    );
                }
                $ainfo['chealth_project'] = $chealth_project;
            }
            $this->assign('userinfo', $user);
            $this->assign('ainfo', $ainfo);
            $this->assign('content', $getinfo);
            $this->assign('dmap', $dmap);
            $this->assign('dmaplist', $dmaplist);
            $this->assign('gmap', $gmap);
            $this->display('enter');
        }
    }

    /**
     * 下载文件
     */
    public function download(){
        $id = I('id');
        $fid = I('fid');
        if(empty($id) || empty($fid)){
            $this->error('参数错误');
        }
        $Enter = D('Chelath/ChealthEnter');
        //检查是否为普通查体报告
        $map = array(
            'id' => $id,
            'uid' => get_uid(),
            'file1' => $fid,
        );
        $res = $Enter->where($map)->find();
        if(!empty($res)){
            R('Core/File/downloadFile',array('id'=>$fid));
            exit();
        }
        unset($map['file1']);
        $map['file2'] = $fid;
        $res = $Enter->where($map)->find();
        if(!empty($res)){
            R('Core/File/downloadFile',array('id'=>$fid));
            exit();
        }
        $this->error('禁止访问!');
    }

    /**
     * 留言反馈
     */
    public function comment(){
        if(IS_POST){
            $model = D('ChealthComment');
            $_POST['uid'] = $this->uid;
            if($model->create()){
                if($model->add() === false){
                    $this->error('系统繁忙，请重试');
                }else{
                    $this->success('感谢您的反馈，我们会继续改进', U('Chealth/Index/index'));
                }
            }else{
                $this->error($model->getError());
            }
        }else{
            $this->display('comment');
        }
    }

    /**
     * 检查是否可以编辑
     * @param $info
     * @return int 1 可以编辑, 0 不可以编辑
     */
    public function check_allow_edit($info){
        if($info['status'] != 1){
            $this->allow_edit_info = '已查体';
            return 0;
        }
        if($info['update_num'] > C('LIMIT_UPDATE_NUM')){
            $this->allow_edit_info = '修改已次数使用完';
            return 0;
        }
        $chealth_edit_day = C('CHEALTH_EDIT_DAY');
        $chealth_edit_day_limit = C('CHEALTH_EDIT_DAY_LIMIT');
        $allow_edit_end_time = $info['chealth_time'] - $chealth_edit_day * 60 * 60 * 24;
        $allow_edit_start_time = $allow_edit_end_time - $chealth_edit_day_limit * 60 * 60 * 24;

        if(NOW_TIME_FORMAT >= $allow_edit_start_time && NOW_TIME_FORMAT <= $allow_edit_end_time){
            return 1;
        }
        $this->allow_edit_info = time_format($allow_edit_start_time, 'Y-m-d') . '至' . time_format($allow_edit_end_time, 'Y-m-d') . '可修改';
        return 0;
    }

    /**
     * 检查用户是否为自动导入没有修改密码的用户
     * 检查是否为没有设置邮箱的用户
     */
    public function defaultUser(){
        $user = D('UcenterMember')->where(array('id'=>$this->uid))->find();
        if($user['type'] == '4'){
//            D('Common/Message')->sendMessageWithoutCheckSelf($this->uid, $content = '', $title = '为了您的账号安全,请修改默认密码.', 'http://'.$_SERVER['HTTP_HOST'].U('Ucenter/Config/password'));
            $this->success('为了您的账号安全,请修改默认密码.', U('Ucenter/Config/password'));
        } elseif (empty($user['email']) or $user['email_verify']==0) {
            D('UcenterMember')->where(array('id'=>$this->uid))->save(array('status'=>3));
            session('temp_login_uid', $this->uid);
            $this->success('以防忘记密码, 请设置找回密码所用的邮箱', U('Ucenter/Member/activate'));
        }
    }

    private function getEnterList($ainfo){
        $day = 60 * 60 * 24;
        $etime = $ainfo['check_exclude_time'];
        $excludeList = array();
        $len = count($etime);
        for($i = 0; $i < $len; $i+=2){
            for ($j = (int)$etime[$i]; $j <= $etime[$i + 1]; $j += $day) {
                $excludeList[] = $j;
            }
        }
        $enterList = array();
        for ($i=(int)$ainfo['check_start_time']; $i <= $ainfo['check_end_time']; $i+=$day) {
            if(!in_array($i, $excludeList)){
                //获取每个可报名时间的报名人数
                $count = D('Chealth/ChealthEnter')->where(array('aid'=>$ainfo['id'],'chealth_time'=>$i))->count();
                $enterList[] = array(
                    'time' => $i,
                    'count' => $count
                );
            }
        }
        return $enterList;
    }

    private function getEnterListFu($ainfo){
        $day = 60 * 60 * 12;
        $etime = $ainfo['check_exclude_time'];
        $excludeList = array();
        $len = count($etime);
        --$day;
        for($i = 0; $i < $len; $i++){
            $excludeList[] = (int)$etime[$i];
            $excludeList[] = (int)($etime[$i] + $day);
        }
        $enterList = array();
        ++$day;
        for ($i=(int)$ainfo['check_start_time']; $i <= $ainfo['check_end_time']; $i+=$day) {
            if(!in_array($i, $excludeList)){
                //获取每个可报名时间的报名人数
                $count = D('Chealth/ChealthEnter')->where(array('aid'=>$ainfo['id'],'chealth_time'=>$i))->count();
                $enterList[] = array(
                    'time' => $i,
                    'count' => $count
                );
            }
        }
        return $enterList;
    }
}